import React, { useRef, useState, useEffect } from 'react'
import style from './cente.module.less'
import { getaccountinfo } from "@/api/account"
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Flex, message, Upload } from 'antd';
import {serverUrl} from "@/utils/comment"

//图片上传
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

export default function Center() {
  const [user, setuser] = useState({});
  //图片上传
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
 // 处理上传变化
 const handleChange = info => {
  if (info.file.status === 'uploading') {
    setLoading(true);
    return;
  }
  if (info.file.status === 'done') {
    setLoading(false);
    // 获取服务器返回的图片 URL
    setImageUrl(info.file.response.imgUrl);
  }
};
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );


  //获取用户信息
  const userInfo = (id) => {
    const data = getaccountinfo({ id: id }).then(res => {
      setuser(res.accountInfo);
    })
  }
  let id = Number(sessionStorage.getItem('userId'));
  useEffect(() => {
    userInfo(id);
  }, []);

  return (
    <div>
      <div className={style.title}>
        个人中心
      </div>
      <div className={style.content}>
        <div className={style.item}>管理员：{id || '暂无'}</div>
        <div className={style.item}>账号：{user.account || '暂无'}</div>
        <div className={style.item}>用户组：{user.userGroup || '暂无'}</div>
        <div className={style.item}>创建时间：{user.ctime || '暂无'}</div>
        <div className={style.item}>用户头像</div>
        <Flex gap="middle" wrap>
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action={`/api/users/avatar_upload?id=${id}`} // 使用模板字符串
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        
        </Flex>
      </div>
    </div>
  )
}
